import { Info } from '@/base/model/Info';
import { getInfo, postInfo, putInfo } from '@/base/api/InfoApi';
import { InfoSort } from '@/base/model/InfoSort';
import { getInfoSortList } from '@/base/api/InfoSortApi';

interface ModifyForms {
  body: string,
  sortId: number,
  images: string[],
  title: string,
  enable?: boolean
}

export class FileEntry {
  constructor(name: string, url: string) {
    this.name = name;
    this.url = url;
  }

  name = '';
  url = '';
}

export class FormBloc {
  form = new Info();
  sortInfo = new InfoSort();
  sortId: number = 0;
  initContent = '';

  load(id: number) {
    return getInfo(id)
      .then((res) => {
        this.form = res.data;
        this.initContent = res.data.body;
        return res;
      });
  }

  loadSort() {
    return getInfoSortList({
      pageIndex: 1,
      pageSize: 15,
      sortDirection: 'ASC',
      sortProperties: ['sort']
    }).then((res) => {
      // @ts-ignore
      this.sortInfo = res.data.items.find(x => x.id === this.sortId);
    });
  }

  save(id: number | '') {
    const entity: ModifyForms = {
      body: this.form.body,
      enable: this.form.enable,
      images: this.form.images,
      sortId: this.sortInfo.id,
      title: this.form.title
    };
    if (id) {
      entity.enable = this.form.enable;
    }
    return id ? putInfo(id, entity) : postInfo(entity);
  }

  resetForm() {
    this.form = new Info();
    this.sortInfo = new InfoSort();
  }
}
